import axios from 'axios';
import { Message } from 'element-ui'
// 接口路径
// const baseUrl = 'http://192.168.1.161:8080'
// const baseUrl = 'http://171.15.132.38:1041/apis'
const baseUrl = 'http://shop.tbmcloud.com.cn/apis'

// 创建axios实例
const service = axios.create({
	timeout: 300000 // 请求超时时间
})

// request请求拦截器
service.interceptors.request.use(res => {
	var a = sessionStorage.getItem("token");
	var flag = res.url.indexOf('/login') == -1 && res.url.indexOf('/mobilecode') == -1 && res.url.indexOf('/checkcode') == -1 && res.url.indexOf('/common/dictdata') == -1
	if (a && a != 'undefined' && flag) {
		res.headers.Authorization = a;
	}
	return res
}, error => {
	Promise.reject(error)
})

// request响应拦截器
service.interceptors.response.use(
	response => {
		let res = response.data
		// 返回处理
		if (res.code == 200) {
			return res;
		} else if (res.code == 401) {
			window.location.href = '/login'
			return res
		} else {
			if (!res.msg) {
				res.msg = ""
			}
			Message.error(res.msg);
			return res;
		}

	},
	error => {
		return Promise.reject(error)
	}
)
// 封装post请求
var postRequest = function (url, data = {}) {
	let sendObject = {
		url: baseUrl + url,
		method: "post",
		headers: {
			'Content-Type': 'application/json;charset=UTF-8'
		},
		data: data
	};
	// sendObject.data = JSON.stringify(data)
	return service(sendObject)
}
// 封装get请求
var getRequest = function (url, data = {}) {
	let sendObject = {
		url: baseUrl + url,
		method: "get",
		headers: {
			'Content-Type': 'application/json;charset=UTF-8'
		},
		params: data
	};
	sendObject.data = JSON.stringify(data)
	return service(sendObject)
}
// 封装自定义方式请求
var setRequest = function (url, data = {}, type, flag = false) {
	let sendObject = {
		url: baseUrl + url,
		method: type,
		headers: {
			'Content-Type': 'application/json;charset=UTF-8'
		},
	};
	if (type == 'put') {
		sendObject.data = data
	} else {
		sendObject.params = data
	}
	// sendObject.data = JSON.stringify(data)
	return service(sendObject)
}
export { postRequest, getRequest, setRequest, baseUrl }